#include "StorageManager.h"
#include <iostream>
#include <algorithm>
#include <cstring> 
namespace MiniDB
{

    const size_t StorageManager::MAX_RECORDS_PER_PAGE = 10; // Simplified for demo

    StorageManager::StorageManager(size_t buffer_size, ReplacementPolicy policy)
        : buffer_manager_(std::make_unique<BufferManager>(buffer_size, policy)),
          next_page_id_(1)
    {

        std::cout << "StorageManager initialized with buffer size: " << buffer_size << std::endl;
        std::cerr << "BufferManager created: " << (buffer_manager_ ? "YES" : "NO") << std::endl;

        // 尝试从文件中恢复数据库状态
        loadDatabaseState();
    }

    StorageManager::~StorageManager()
    {
        std::cout << "StorageManager destructor called, calling flushAll()..." << std::endl;
        flushAll();

        // 保存数据库状态到文件
        saveDatabaseState();

        std::cout << "StorageManager destroyed" << std::endl;
    }

    bool StorageManager::createTable(const std::string &table_name)
    {
        if (tableExists(table_name))
        {
            std::cerr << "Error: Table '" << table_name << "' already exists" << std::endl;
            return false;
        }

        tables_.emplace(table_name, TableMetadata(table_name));

        // Allocate first page for the table
        int first_page = allocatePage(table_name);

        std::cout << "Table '" << table_name << "' created with first page: " << first_page << std::endl;
        return true;
    }

    bool StorageManager::restoreTableMetadata(const std::string &table_name, int root_page_id, size_t record_count, size_t total_size)
    {
        if (tableExists(table_name))
        {
            std::cerr << "Warning: Table '" << table_name << "' already exists, skipping restoration" << std::endl;
            return true;
        }

        // 创建表元数据结构
        TableMetadata metadata(table_name);
        metadata.page_ids.push_back(root_page_id);
        metadata.record_count = record_count;
        metadata.total_size = total_size;

        // 添加到表映射
        tables_[table_name] = metadata;

        // 更新next_page_id以避免冲突
        if (root_page_id >= static_cast<int>(next_page_id_))
        {
            next_page_id_ = root_page_id + 1;
        }

        std::cout << "Restored metadata for table '" << table_name << "' (page " << root_page_id << ")" << std::endl;
        return true;
    }

    bool StorageManager::dropTable(const std::string &table_name)
    {
        auto it = tables_.find(table_name);
        if (it == tables_.end())
        {
            std::cerr << "Error: Table '" << table_name << "' does not exist" << std::endl;
            return false;
        }

        // Deallocate all pages
        for (int page_id : it->second.page_ids)
        {
            deallocatePage(page_id, table_name);
        }

        tables_.erase(it);

        std::cout << "Table '" << table_name << "' dropped" << std::endl;
        return true;
    }

    bool StorageManager::tableExists(const std::string &table_name) const
    {
        return tables_.find(table_name) != tables_.end();
    }

    std::vector<std::string> StorageManager::getTableNames() const
    {
        std::vector<std::string> names;
        names.reserve(tables_.size());
        for (const auto &pair : tables_)
        {
            names.push_back(pair.first);
        }
        return names;
    }

    std::shared_ptr<Page> StorageManager::getPage(int page_id)
    {
        return buffer_manager_->getPage(page_id);
    }

    bool StorageManager::readPage(int page_id, void *buffer, size_t size)
    {
        auto page = buffer_manager_->getPage(page_id);
        if (!page)
            return false;

        bool result = page->readData(0, buffer, size);
        buffer_manager_->releasePage(page_id);
        return result;
    }

    bool StorageManager::writePage(int page_id, const void *data, size_t size)
    {
        auto page = buffer_manager_->getPage(page_id);
        if (!page)
            return false;

        bool result = page->writeData(0, data, size);
        buffer_manager_->releasePage(page_id);
        return result;
    }

    bool StorageManager::flushPage(int page_id)
    {
        return buffer_manager_->flushPage(page_id);
    }

    bool StorageManager::flushAll()
    {
        return buffer_manager_->flushAll();
    }

    void StorageManager::releasePage(int page_id)
    {
        buffer_manager_->releasePage(page_id);
    }

    bool StorageManager::insertRecord(const std::string &table_name, const Record &record)
    {
        if (!tableExists(table_name))
        {
            std::cerr << "Error: Table '" << table_name << "' does not exist" << std::endl;
            return false;
        }

        auto &table = tables_[table_name];

        // Find a page with enough space or allocate new page
        int target_page_id = -1;
        for (int page_id : table.page_ids)
        {
            auto page = getPage(page_id);
            if (page && page->canFit(record.size()))
            {
                target_page_id = page_id;
                releasePage(page_id);
                break;
            }
            if (page)
                releasePage(page_id);
        }

        // If no suitable page found, allocate new one
        if (target_page_id == -1)
        {
            target_page_id = allocatePage(table_name);
            if (target_page_id == -1)
            {
                std::cerr << "Error: Failed to allocate page for table '" << table_name << "'" << std::endl;
                return false;
            }
        }

        // Serialize record and write to page
        std::vector<char> buffer;
        if (!serializeRecord(record, buffer))
        {
            std::cerr << "Error: Failed to serialize record" << std::endl;
            return false;
        }

        auto page = getPage(target_page_id);
        if (!page)
        {
            std::cerr << "Error: Failed to get page " << target_page_id << std::endl;
            return false;
        }

        size_t offset = page->getUsedSpace();
        if (!page->writeData(offset, buffer.data(), buffer.size()))
        {
            std::cerr << "Error: Failed to write record to page" << std::endl;
            releasePage(target_page_id);
            return false;
        }

        // Force flush the page to disk immediately after writing
        if (!flushPage(target_page_id))
        {
            std::cerr << "Warning: Failed to flush page " << target_page_id << " to disk" << std::endl;
        }

        releasePage(target_page_id);

        // Update table metadata
        table.record_count++;
        table.total_size += record.size();

        std::cout << "Record inserted into table '" << table_name << "' (ID: " << record.id << ") and flushed to disk" << std::endl;
        return true;
    }

    bool StorageManager::deleteRecord(const std::string &table_name, int record_id)
    {
        if (!tableExists(table_name))
        {
            std::cerr << "Error: Table '" << table_name << "' does not exist" << std::endl;
            return false;
        }

        auto &table = tables_[table_name];

        // Simple implementation - mark record as deleted
        // In a real system, this would require scanning pages
        for (int page_id : table.page_ids)
        {
            auto page = getPage(page_id);
            if (!page)
                continue;

            // Scan page for the record (simplified)
            // In reality, this would need proper record scanning logic
            releasePage(page_id);
        }

        // For demo purposes, just decrement count
        if (table.record_count > 0)
        {
            table.record_count--;
            std::cout << "Record " << record_id << " marked as deleted from table '" << table_name << "'" << std::endl;
            return true;
        }

        return false;
    }

    bool StorageManager::updateRecord(const std::string &table_name, int record_id, const Record &new_record)
    {
        if (!tableExists(table_name))
        {
            std::cerr << "Error: Table '" << table_name << "' does not exist" << std::endl;
            return false;
        }

        // Simplified implementation - delete and insert
        if (deleteRecord(table_name, record_id))
        {
            return insertRecord(table_name, new_record);
        }

        return false;
    }

    std::vector<Record> StorageManager::getRecords(const std::string &table_name)
    {
        std::vector<Record> records;

        if (!tableExists(table_name))
        {
            std::cerr << "Error: Table '" << table_name << "' does not exist" << std::endl;
            return records;
        }

        auto &table = tables_[table_name];

        // Scan all pages allocated to this table
        for (int page_id : table.page_ids)
        {
            auto page = getPage(page_id);
            if (!page)
            {
                std::cerr << "Warning: Could not access page " << page_id << " for table '" << table_name << "'" << std::endl;
                continue;
            }

            // Scan the page for records
            size_t offset = 0;
            while (offset < page->getUsedSpace())
            {
                // Check if we have enough data for a record header (ID + data_size + is_deleted)
                if (offset + sizeof(int) + sizeof(size_t) + sizeof(bool) > page->getUsedSpace())
                {
                    break; // Not enough data for a complete record header
                }

                // First, read just the record header to determine data size
                char header_buffer[sizeof(int) + sizeof(size_t) + sizeof(bool)];
                if (!page->readData(offset, header_buffer, sizeof(header_buffer)))
                {
                    std::cerr << "Error: Failed to read record header from page " << page_id << std::endl;
                    break;
                }

                // Extract data size from header
                size_t data_size;
                std::memcpy(&data_size, header_buffer + sizeof(int), sizeof(data_size));

                // Calculate total record size
                size_t total_record_size = sizeof(int) + sizeof(size_t) + data_size + sizeof(bool);

                // Check if we have enough data for the complete record
                if (offset + total_record_size > page->getUsedSpace())
                {
                    std::cerr << "Warning: Incomplete record at offset " << offset << " in page " << page_id << std::endl;
                    break;
                }

                // Now read the complete record
                std::vector<char> record_buffer(total_record_size);
                if (!page->readData(offset, record_buffer.data(), total_record_size))
                {
                    std::cerr << "Error: Failed to read complete record from page " << page_id << std::endl;
                    break;
                }

                Record record;
                size_t bytes_read = 0;
                if (deserializeRecord(record_buffer, record, bytes_read))
                {
                    // Only add non-deleted records
                    if (!record.is_deleted)
                    {
                        records.push_back(record);
                    }
                    offset += bytes_read;
                }
                else
                {
                    std::cerr << "Warning: Failed to deserialize record at offset " << offset << " in page " << page_id << std::endl;
                    break; // Stop scanning this page if we can't deserialize
                }
            }

            releasePage(page_id);
        }

        std::cout << "Retrieved " << records.size() << " records from table '" << table_name << "'" << std::endl;
        return records;
    }

    Record StorageManager::getRecord(const std::string &table_name, int record_id)
    {
        if (!tableExists(table_name))
        {
            return Record();
        }

        // Simplified implementation
        return Record(record_id, "Sample data for record " + std::to_string(record_id));
    }

    const CacheStats &StorageManager::getCacheStats() const
    {
        return buffer_manager_->getStats();
    }

    void StorageManager::resetCacheStats()
    {
        buffer_manager_->resetStats();
    }

    void StorageManager::resizeBuffer(size_t new_size)
    {
        buffer_manager_->resize(new_size);
    }

    void StorageManager::setReplacementPolicy(ReplacementPolicy policy)
    {
        buffer_manager_->setReplacementPolicy(policy);
    }

    size_t StorageManager::getTableSize(const std::string &table_name) const
    {
        auto it = tables_.find(table_name);
        return (it != tables_.end()) ? it->second.total_size : 0;
    }

    size_t StorageManager::getRecordCount(const std::string &table_name) const
    {
        auto it = tables_.find(table_name);
        return (it != tables_.end()) ? it->second.record_count : 0;
    }

    void StorageManager::printTableInfo(const std::string &table_name) const
    {
        auto it = tables_.find(table_name);
        if (it == tables_.end())
        {
            std::cout << "Table '" << table_name << "' does not exist" << std::endl;
            return;
        }

        const auto &table = it->second;
        std::cout << "=== Table Information ===" << std::endl;
        std::cout << "Name: " << table.table_name << std::endl;
        std::cout << "Pages: " << table.page_ids.size() << std::endl;
        std::cout << "Records: " << table.record_count << std::endl;
        std::cout << "Total Size: " << table.total_size << " bytes" << std::endl;
        std::cout << "Page IDs: ";
        for (int page_id : table.page_ids)
        {
            std::cout << page_id << " ";
        }
        std::cout << std::endl;
    }

    int StorageManager::allocatePage(const std::string &table_name)
    {
        int page_id = next_page_id_++;
        tables_[table_name].page_ids.push_back(page_id);
        page_to_table_[page_id] = table_name;

        std::cout << "Allocated page " << page_id << " for table '" << table_name << "'" << std::endl;
        return page_id;
    }

    void StorageManager::deallocatePage(int page_id, const std::string &table_name)
    {
        auto it = page_to_table_.find(page_id);
        if (it != page_to_table_.end())
        {
            page_to_table_.erase(it);
        }

        auto &table_pages = tables_[table_name].page_ids;
        table_pages.erase(std::remove(table_pages.begin(), table_pages.end(), page_id), table_pages.end());

        std::cout << "Deallocated page " << page_id << " from table '" << table_name << "'" << std::endl;
    }

    bool StorageManager::serializeRecord(const Record &record, std::vector<char> &buffer)
    {
        try
        {
            // Serialize record ID
            buffer.insert(buffer.end(), reinterpret_cast<const char *>(&record.id), reinterpret_cast<const char *>(&record.id) + sizeof(record.id));

            // Serialize data length
            size_t data_size = record.data.size();
            buffer.insert(buffer.end(), reinterpret_cast<const char *>(&data_size), reinterpret_cast<const char *>(&data_size) + sizeof(data_size));

            // Serialize data
            buffer.insert(buffer.end(), record.data.begin(), record.data.end());

            // Serialize deleted flag
            buffer.insert(buffer.end(), reinterpret_cast<const char *>(&record.is_deleted), reinterpret_cast<const char *>(&record.is_deleted) + sizeof(record.is_deleted));

            return true;
        }
        catch (const std::exception &e)
        {
            std::cerr << "Serialization error: " << e.what() << std::endl;
            return false;
        }
    }

    bool StorageManager::deserializeRecord(const std::vector<char> &buffer, Record &record, size_t &bytes_read)
    {
        try
        {
            size_t offset = 0;

            // Deserialize record ID
            std::memcpy(&record.id, buffer.data() + offset, sizeof(record.id));
            offset += sizeof(record.id);

            // Deserialize data length
            size_t data_size;
            std::memcpy(&data_size, buffer.data() + offset, sizeof(data_size));
            offset += sizeof(data_size);

            // Deserialize data
            record.data.assign(buffer.begin() + offset, buffer.begin() + offset + data_size);
            offset += data_size;

            // Deserialize deleted flag
            std::memcpy(&record.is_deleted, buffer.data() + offset, sizeof(record.is_deleted));
            offset += sizeof(record.is_deleted);

            bytes_read = offset;
            return true;
        }
        catch (const std::exception &e)
        {
            std::cerr << "Deserialization error: " << e.what() << std::endl;
            return false;
        }
    }
std::vector<JoinResult> StorageManager::joinTables(const std::vector<std::string> &table_names, const std::string &join_condition)
{
    std::vector<JoinResult> results;

    // 标记参数为已使用，避免警告
    (void)join_condition;

    // Validate all tables exist
    for (const auto &table_name : table_names)
    {
        if (!tableExists(table_name))
        {
            std::cerr << "Error: Table '" << table_name << "' does not exist" << std::endl;
            return results;
        }
    }

    if (table_names.empty())
    {
        return results;
    }

    // For demonstration, we'll perform a simple cross join based on record IDs
    // In a real implementation, this would parse the join_condition and perform proper joins

    // Get all records from all tables
    std::vector<std::vector<Record>> all_table_records;
    for (const auto &table_name : table_names)
    {
        auto records = getRecords(table_name);
        all_table_records.push_back(records);
    }

    // Find maximum number of records across all tables
    size_t max_records = 0;
    for (const auto &table_records : all_table_records)
    {
        max_records = std::max(max_records, table_records.size());
    }

    // Perform cross join (simplified)
    for (size_t i = 0; i < max_records; ++i)
    {
        JoinResult result(i + 1);

        for (size_t j = 0; j < table_names.size(); ++j)
        {
            const auto &table_name = table_names[j];
            const auto &table_records = all_table_records[j];

            if (i < table_records.size())
            {
                const auto &record = table_records[i];
                if (!record.is_deleted)
                {
                    result.table_data[table_name] = record.data;
                }
            }
            else
            {
                result.table_data[table_name] = "[No matching record]";
            }
        }

        // Only add result if at least one table has data
        bool has_data = false;
        for (const auto &pair : result.table_data)
        {
            if (pair.second != "[No matching record]")
            {
                has_data = true;
                break;
            }
        }

        if (has_data)
        {
            results.push_back(result);
        }
    }

    std::cout << "Multi-table join completed for " << table_names.size() << " tables, "
              << results.size() << " results found" << std::endl;

    return results;
}
    // 改进的多表联查实现 - 支持不同的JOIN类型
    std::vector<JoinResult> StorageManager::joinTablesWithCondition(const std::vector<std::string> &table_names,
                                                                    const std::string &join_type, const std::string &condition)
    {
        std::vector<JoinResult> results;

        // 验证表是否存在
        for (const auto &table_name : table_names)
        {
            if (!tableExists(table_name))
            {
                std::cerr << "Error: Table '" << table_name << "' does not exist" << std::endl;
                return results;
            }
        }

        if (table_names.size() < 2)
        {
            std::cerr << "Error: Need at least 2 tables for join operation" << std::endl;
            return results;
        }

        // 获取所有表的记录
        std::vector<std::vector<Record>> all_table_records;
        for (const auto &table_name : table_names)
        {
            auto records = getRecords(table_name);
            all_table_records.push_back(records);
        }

        // 根据JOIN类型执行相应的操作
        if (join_type == "INNER" || join_type == "inner")
        {
            performInnerJoinAdvanced(table_names, all_table_records, results, condition);
        }
        else if (join_type == "LEFT" || join_type == "left")
        {
            performLeftJoinAdvanced(table_names, all_table_records, results, condition);
        }
        else if (join_type == "RIGHT" || join_type == "right")
        {
            performRightJoinAdvanced(table_names, all_table_records, results, condition);
        }
        else if (join_type == "FULL" || join_type == "full")
        {
            performFullJoinAdvanced(table_names, all_table_records, results, condition);
        }
        else if (join_type == "CROSS" || join_type == "cross")
        {
            performCrossJoin(table_names, all_table_records, results);
        }
        else
        {
            std::cerr << "Warning: Unknown join type '" << join_type << "', performing cross join" << std::endl;
            performCrossJoin(table_names, all_table_records, results);
        }

        std::cout << join_type << " join completed for " << table_names.size() << " tables, "
                  << results.size() << " results found" << std::endl;

        return results;
    }

    // 高级内连接实现
    void StorageManager::performInnerJoinAdvanced(const std::vector<std::string> &table_names,
                                                  const std::vector<std::vector<Record>> &all_records,
                                                  std::vector<JoinResult> &results,
                                                  const std::string &condition)
    {
        // 解析连接条件
        auto [left_table, left_col, right_table, right_col] = parseJoinCondition(condition);

        size_t left_idx = findTableIndex(table_names, left_table);
        size_t right_idx = findTableIndex(table_names, right_table);

        if (left_idx == std::string::npos || right_idx == std::string::npos)
        {
            std::cerr << "Error: Could not find table indices for join condition" << std::endl;
            return;
        }

        const auto &left_records = all_records[left_idx];
        const auto &right_records = all_records[right_idx];

        int result_id = 1;

        for (const auto &left_rec : left_records)
        {
            if (left_rec.is_deleted)
                continue;

            for (const auto &right_rec : right_records)
            {
                if (right_rec.is_deleted)
                    continue;

                // 检查连接条件 (简化实现，基于记录ID)
                if (matchesJoinCondition(left_rec, right_rec, left_col, right_col))
                {
                    JoinResult result(result_id++);
                    result.table_data[table_names[left_idx]] = left_rec.data;
                    result.table_data[table_names[right_idx]] = right_rec.data;

                    // 添加其他表的空数据
                    for (size_t i = 0; i < table_names.size(); ++i)
                    {
                        if (i != left_idx && i != right_idx)
                        {
                            result.table_data[table_names[i]] = "[N/A]";
                        }
                    }

                    results.push_back(result);
                }
            }
        }
    }

    // 高级左连接实现
    void StorageManager::performLeftJoinAdvanced(const std::vector<std::string> &table_names,
                                                 const std::vector<std::vector<Record>> &all_records,
                                                 std::vector<JoinResult> &results,
                                                 const std::string &condition)
    {
        auto [left_table, left_col, right_table, right_col] = parseJoinCondition(condition);

        size_t left_idx = findTableIndex(table_names, left_table);
        size_t right_idx = findTableIndex(table_names, right_table);

        if (left_idx == std::string::npos)
        {
            std::cerr << "Error: Left table not found" << std::endl;
            return;
        }

        const auto &left_records = all_records[left_idx];
        const auto &right_records = (right_idx != std::string::npos) ? all_records[right_idx] : std::vector<Record>();

        int result_id = 1;

        for (const auto &left_rec : left_records)
        {
            if (left_rec.is_deleted)
                continue;

            bool matched = false;

            if (!right_records.empty())
            {
                for (const auto &right_rec : right_records)
                {
                    if (right_rec.is_deleted)
                        continue;

                    if (matchesJoinCondition(left_rec, right_rec, left_col, right_col))
                    {
                        JoinResult result(result_id++);
                        result.table_data[table_names[left_idx]] = left_rec.data;
                        result.table_data[table_names[right_idx]] = right_rec.data;

                        for (size_t i = 0; i < table_names.size(); ++i)
                        {
                            if (i != left_idx && i != right_idx)
                            {
                                result.table_data[table_names[i]] = "[N/A]";
                            }
                        }

                        results.push_back(result);
                        matched = true;
                    }
                }
            }

            // 如果没有匹配，添加左表记录，右表为NULL
            if (!matched)
            {
                JoinResult result(result_id++);
                result.table_data[table_names[left_idx]] = left_rec.data;
                if (right_idx != std::string::npos)
                {
                    result.table_data[table_names[right_idx]] = "NULL";
                }

                for (size_t i = 0; i < table_names.size(); ++i)
                {
                    if (i != left_idx && i != right_idx)
                    {
                        result.table_data[table_names[i]] = "[N/A]";
                    }
                }

                results.push_back(result);
            }
        }
    }

    // 高级右连接实现
    void StorageManager::performRightJoinAdvanced(const std::vector<std::string> &table_names,
                                                  const std::vector<std::vector<Record>> &all_records,
                                                  std::vector<JoinResult> &results,
                                                  const std::string &condition)
    {
        // 右连接可以通过交换表顺序实现为左连接
        auto [left_table, left_col, right_table, right_col] = parseJoinCondition(condition);

        // 交换表和列
        std::string temp_table = left_table;
        std::string temp_col = left_col;
        left_table = right_table;
        left_col = right_col;
        right_table = temp_table;
        right_col = temp_col;

        performLeftJoinAdvanced(table_names, all_records, results, left_table + "." + left_col + "=" + right_table + "." + right_col);
    }

    // 高级全连接实现
    void StorageManager::performFullJoinAdvanced(const std::vector<std::string> &table_names,
                                                 const std::vector<std::vector<Record>> &all_records,
                                                 std::vector<JoinResult> &results,
                                                 const std::string &condition)
    {
        // 全连接 = 左连接 + 右连接（去除重复）
        std::vector<JoinResult> left_results, right_results;

        performLeftJoinAdvanced(table_names, all_records, left_results, condition);

        // 执行右连接
        auto [left_table, left_col, right_table, right_col] = parseJoinCondition(condition);
        std::string swapped_condition = right_table + "." + right_col + "=" + left_table + "." + left_col;
        performLeftJoinAdvanced(table_names, all_records, right_results, swapped_condition);

        // 合并结果，避免重复
        results = left_results;

        for (const auto &right_result : right_results)
        {
            bool is_duplicate = false;
            for (const auto &left_result : left_results)
            {
                if (resultsAreEqual(left_result, right_result))
                {
                    is_duplicate = true;
                    break;
                }
            }

            if (!is_duplicate)
            {
                results.push_back(right_result);
            }
        }
    }

    // 解析连接条件的辅助方法
    std::tuple<std::string, std::string, std::string, std::string>
    StorageManager::parseJoinCondition(const std::string &condition)
    {
        std::string left_table, left_col, right_table, right_col;

        // 解析形如 "users.id = orders.user_id" 的条件
        size_t equal_pos = condition.find('=');
        if (equal_pos != std::string::npos)
        {
            std::string left_part = condition.substr(0, equal_pos);
            std::string right_part = condition.substr(equal_pos + 1);

            // 移除空格
            left_part.erase(std::remove(left_part.begin(), left_part.end(), ' '), left_part.end());
            right_part.erase(std::remove(right_part.begin(), right_part.end(), ' '), right_part.end());

            // 解析左边：table.column
            size_t dot_pos_left = left_part.find('.');
            if (dot_pos_left != std::string::npos)
            {
                left_table = left_part.substr(0, dot_pos_left);
                left_col = left_part.substr(dot_pos_left + 1);
            }

            // 解析右边：table.column
            size_t dot_pos_right = right_part.find('.');
            if (dot_pos_right != std::string::npos)
            {
                right_table = right_part.substr(0, dot_pos_right);
                right_col = right_part.substr(dot_pos_right + 1);
            }
        }

        return std::make_tuple(left_table, left_col, right_table, right_col);
    }

 bool StorageManager::matchesJoinCondition(const Record &left_rec, const Record &right_rec,
                                          const std::string &left_col, const std::string &right_col)
{
    // 标记未使用的参数为已使用，避免警告
    (void)left_col;
    (void)right_col;

    // 简化实现：基于记录ID进行匹配
    // 实际实现应该解析记录数据并根据指定列进行比较
    return left_rec.id == right_rec.id;
}

    // 检查两个结果是否相等的辅助方法
    bool StorageManager::resultsAreEqual(const JoinResult &result1, const JoinResult &result2)
    {
        if (result1.table_data.size() != result2.table_data.size())
            return false;

        for (const auto &pair : result1.table_data)
        {
            auto it = result2.table_data.find(pair.first);
            if (it == result2.table_data.end() || it->second != pair.second)
                return false;
        }

        return true;
    }

    // 查找表索引的辅助方法
    size_t StorageManager::findTableIndex(const std::vector<std::string> &table_names, const std::string &table_name)
    {
        for (size_t i = 0; i < table_names.size(); ++i)
        {
            if (table_names[i] == table_name)
            {
                return i;
            }
        }
        return std::string::npos;
    }

    // 原始的交叉连接实现（用于向后兼容）
    void StorageManager::performCrossJoin(const std::vector<std::string> &table_names,
                                          const std::vector<std::vector<Record>> &all_records,
                                          std::vector<JoinResult> &results)
    {
        // Find maximum number of records across all tables
        size_t max_records = 0;
        for (const auto &table_records : all_records)
        {
            max_records = std::max(max_records, table_records.size());
        }

        for (size_t i = 0; i < max_records; ++i)
        {
            JoinResult result(i + 1);

            for (size_t j = 0; j < table_names.size(); ++j)
            {
                const auto &table_records = all_records[j];

                if (i < table_records.size())
                {
                    const auto &record = table_records[i];
                    if (!record.is_deleted)
                    {
                        result.table_data[table_names[j]] = record.data;
                    }
                }
                else
                {
                    result.table_data[table_names[j]] = "[No matching record]";
                }
            }

            bool has_data = false;
            for (const auto &pair : result.table_data)
            {
                if (pair.second != "[No matching record]")
                {
                    has_data = true;
                    break;
                }
            }

            if (has_data)
            {
                results.push_back(result);
            }
        }
    }

    // 数据持久化实现
    bool StorageManager::saveDatabaseState()
    {
        std::cout << "Saving database state to file..." << std::endl;

        try
        {
            // 保存表元数据
            if (!saveTableMetadata())
            {
                std::cerr << "Failed to save table metadata" << std::endl;
                return false;
            }

            // 确保所有页面都被刷新到磁盘
            flushAll();

            std::cout << "Database state saved successfully" << std::endl;
            return true;
        }
        catch (const std::exception &e)
        {
            std::cerr << "Error saving database state: " << e.what() << std::endl;
            return false;
        }
    }

    bool StorageManager::loadDatabaseState()
    {
        std::cout << "Loading database state from file..." << std::endl;

        try
        {
            // 加载表元数据
            if (!loadTableMetadata())
            {
                std::cout << "No previous database state found, starting fresh" << std::endl;
                return false; // 这不是错误，只是没有之前的状态
            }

            std::cout << "Database state loaded successfully" << std::endl;
            return true;
        }
        catch (const std::exception &e)
        {
            std::cerr << "Error loading database state: " << e.what() << std::endl;
            return false;
        }
    }

    bool StorageManager::saveTableMetadata()
{
    try
    {
        // 创建一个特殊的元数据页面来存储表信息
        const int METADATA_PAGE_ID = 0;
        auto page = getPage(METADATA_PAGE_ID);
        if (!page)
        {
            std::cerr << "Failed to get metadata page" << std::endl;
            return false;
        }

        // 序列化表元数据
        std::vector<char> metadata_buffer;

        // 写入表数量
        size_t table_count = tables_.size();
        metadata_buffer.insert(metadata_buffer.end(),
                             reinterpret_cast<const char*>(&table_count),
                             reinterpret_cast<const char*>(&table_count) + sizeof(table_count));

        // 为每个表写入元数据
        for (const auto& table_pair : tables_)
        {
            const std::string& table_name = table_pair.first;
            const TableMetadata& metadata = table_pair.second;

            // 表名长度和表名
            size_t name_size = table_name.size();
            metadata_buffer.insert(metadata_buffer.end(),
                                 reinterpret_cast<const char*>(&name_size),
                                 reinterpret_cast<const char*>(&name_size) + sizeof(name_size));
            metadata_buffer.insert(metadata_buffer.end(),
                                 table_name.begin(), table_name.end());

            // 页面ID数量和页面ID列表
            size_t page_count = metadata.page_ids.size();
            metadata_buffer.insert(metadata_buffer.end(),
                                 reinterpret_cast<const char*>(&page_count),
                                 reinterpret_cast<const char*>(&page_count) + sizeof(page_count));

            for (int page_id : metadata.page_ids)
            {
                metadata_buffer.insert(metadata_buffer.end(),
                                     reinterpret_cast<const char*>(&page_id),
                                     reinterpret_cast<const char*>(&page_id) + sizeof(page_id));
            }

            // 记录数量和总大小
            metadata_buffer.insert(metadata_buffer.end(),
                                 reinterpret_cast<const char*>(&metadata.record_count),
                                 reinterpret_cast<const char*>(&metadata.record_count) + sizeof(metadata.record_count));
            metadata_buffer.insert(metadata_buffer.end(),
                                 reinterpret_cast<const char*>(&metadata.total_size),
                                 reinterpret_cast<const char*>(&metadata.total_size) + sizeof(metadata.total_size));
        }

        // 写入元数据页面
        if (!page->writeData(0, metadata_buffer.data(), metadata_buffer.size()))
        {
            std::cerr << "Failed to write metadata to page" << std::endl;
            releasePage(METADATA_PAGE_ID);
            return false;
        }

        // 强制刷新到磁盘
        if (!flushPage(METADATA_PAGE_ID))
        {
            std::cerr << "Failed to flush metadata page to disk" << std::endl;
        }

        releasePage(METADATA_PAGE_ID);
        return true;
    }
    catch (const std::exception &e)
    {
        std::cerr << "Error saving table metadata: " << e.what() << std::endl;
        return false;
    }
}

    bool StorageManager::loadTableMetadata()
    {
        try
        {
            // 尝试读取元数据页面
            const int METADATA_PAGE_ID = 0;
            auto page = getPage(METADATA_PAGE_ID);
            if (!page)
            {
                // 没有元数据页面，说明是全新的数据库
                return false;
            }

            // 检查页面是否有数据
            if (page->getUsedSpace() == 0)
            {
                releasePage(METADATA_PAGE_ID);
                return false;
            }

            // 读取元数据
            std::vector<char> metadata_buffer(page->getUsedSpace());
            if (!page->readData(0, metadata_buffer.data(), metadata_buffer.size()))
            {
                std::cerr << "Failed to read metadata from page" << std::endl;
                releasePage(METADATA_PAGE_ID);
                return false;
            }

            releasePage(METADATA_PAGE_ID);

            // 反序列化元数据
            size_t offset = 0;

            // 读取表数量
            if (offset + sizeof(size_t) > metadata_buffer.size())
            {
                std::cerr << "Invalid metadata format: cannot read table count" << std::endl;
                return false;
            }

            size_t table_count;
            std::memcpy(&table_count, metadata_buffer.data() + offset, sizeof(table_count));
            offset += sizeof(table_count);

            // 读取每个表的元数据
            for (size_t i = 0; i < table_count; ++i)
            {
                // 读取表名
                if (offset + sizeof(size_t) > metadata_buffer.size())
                {
                    std::cerr << "Invalid metadata format: cannot read table name size" << std::endl;
                    return false;
                }

                size_t name_size;
                std::memcpy(&name_size, metadata_buffer.data() + offset, sizeof(name_size));
                offset += sizeof(name_size);

                if (offset + name_size > metadata_buffer.size())
                {
                    std::cerr << "Invalid metadata format: table name data incomplete" << std::endl;
                    return false;
                }

                std::string table_name(metadata_buffer.begin() + offset,
                                     metadata_buffer.begin() + offset + name_size);
                offset += name_size;

                // 读取页面ID列表
                if (offset + sizeof(size_t) > metadata_buffer.size())
                {
                    std::cerr << "Invalid metadata format: cannot read page count" << std::endl;
                    return false;
                }

                size_t page_count;
                std::memcpy(&page_count, metadata_buffer.data() + offset, sizeof(page_count));
                offset += sizeof(page_count);

                std::vector<int> page_ids;
                for (size_t j = 0; j < page_count; ++j)
                {
                    if (offset + sizeof(int) > metadata_buffer.size())
                    {
                        std::cerr << "Invalid metadata format: page ID data incomplete" << std::endl;
                        return false;
                    }

                    int page_id;
                    std::memcpy(&page_id, metadata_buffer.data() + offset, sizeof(page_id));
                    offset += sizeof(page_id);
                    page_ids.push_back(page_id);
                }

                // 读取记录数量和总大小
                if (offset + sizeof(size_t) * 2 > metadata_buffer.size())
                {
                    std::cerr << "Invalid metadata format: cannot read record stats" << std::endl;
                    return false;
                }

                size_t record_count, total_size;
                std::memcpy(&record_count, metadata_buffer.data() + offset, sizeof(record_count));
                offset += sizeof(record_count);
                std::memcpy(&total_size, metadata_buffer.data() + offset, sizeof(total_size));
                offset += sizeof(total_size);

                // 恢复表元数据
                TableMetadata metadata(table_name);
                metadata.page_ids = page_ids;
                metadata.record_count = record_count;
                metadata.total_size = total_size;

                tables_[table_name] = metadata;

                // 更新next_page_id
                for (int page_id : page_ids)
                {
                    if (page_id >= static_cast<int>(next_page_id_))
                    {
                        next_page_id_ = page_id + 1;
                    }
                }

                std::cout << "Restored table '" << table_name << "' with "
                          << record_count << " records on " << page_ids.size() << " pages" << std::endl;
            }

            return true;
        }
        catch (const std::exception &e)
        {
            std::cerr << "Error loading table metadata: " << e.what() << std::endl;
            return false;
        }
    }

} // namespace MiniDB
